package net.findkrypton.po;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import net.findkrypton.GameInfo;
import net.findkrypton.entity.ArrayBase;
import net.findkrypton.event.RunningStateEvent;
import net.findkrypton.util.UPath;
import net.jumpengine.M;
import net.jumpengine.Manager;
import net.jumpengine.enume.GameState;
import net.jumpengine.util.UComm;
import net.jumpengine.util.UIO;

/**
 * 存档加载与保存类
 * <br /><br />
 * <b>作者:&nbsp;</b>张天文 <br />
 * <b>日期:&nbsp;</b>2020年3月27日 下午7:26:39<br />
 * @date
 */
public class LoadSave {
	private static List<SaveFile> list=new ArrayList<SaveFile>();
	private static int saveIndex=-1;
	
	/** 存档读取信息并存储到集合 */
	public static void load() {
		File f=new File(UPath.projectPath("/save"));
		
		list.clear();
		
		File[] listFiles = f.listFiles(new FileFilter() {
			private FileInputStream fis;
			private String ext;
			private boolean equals=false;
			@Override
			public boolean accept(File pathname) {
				if(pathname.length()<300 || pathname.length()>1800)return false;
				
				ext=UComm.extName(pathname.getAbsolutePath());
				if(!UComm.equals(ext, "stm"))return false;
				try {
					fis=new FileInputStream(pathname);
					equals=fis.read()==10;
					equals= equals && (fis.read()==27);
					return equals;
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				return false;
			}
		});
		
		FileInputStream fis=null;
		int tmp;
		int width = 0,height = 0,useTime=0,noFlag=0,level = 0;
		SaveFile save;
		for(File file:listFiles) {
			try {
				fis=new FileInputStream(file);
				for(int i=0;i<13;i++) {
					tmp=fis.read();
					if(i==4)width=tmp;
					if(i==5)height=tmp;
					if(i>5 && i<10) {
						useTime+=tmp<<((i-6)*8);
					}
					if(i==10)noFlag=tmp;
					if(i==11)noFlag+=tmp<<8;
					if(i==12)level=tmp;
				}
				save=new SaveFile(new Date(file.lastModified()), level, width, height, useTime, noFlag);
				save.setPath(file);
				list.add(save);
				
				useTime=0;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				if(fis!=null) {
					try { fis.close(); } catch (IOException e) { e.printStackTrace(); }
				}
			}
		}
		
		list.sort(new Comparator<SaveFile>() {
			@Override
			public int compare(SaveFile o1, SaveFile o2) {
				return o2.getEditDate().compareTo(o1.getEditDate());
			}
		});
	}
	
	public static String loadData(int index) {
		SaveFile saveFile = list.get(index);
		if(saveFile==null || saveFile.getPath()==null || !saveFile.getPath().exists()) {
			return "无法获取存档或存档损坏,清选择其它存档!";
		}
		System.out.println(saveFile);
		BufferedReader read=null;
		try {
			read=new BufferedReader(new FileReader(saveFile.getPath()));
			read.skip(13);
			int[] ints=new int[saveFile.getWidth()*saveFile.getHeight()];
			int tmp,ind=0;
			while((tmp=read.read())>=0) {
				ints[ind]=tmp;
				ind++;
			}
			RunningStateEvent event = (RunningStateEvent) M.e().getStateEvent(GameState.running);
			if(event.getInfo()==null) {
				event.setInfo(new GameInfo(saveFile.getLevel()));
			}
			event.setReLoad(saveFile, ints);
			Manager.setState(GameState.running);
			return null;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(read!=null) {
				try { read.close(); } catch (IOException e) { e.printStackTrace(); }
			}
		}
		return null;
	}
	
	public static int savePostion() {
		if(list.size()<10)return list.size();
		saveIndex++;
		saveIndex=saveIndex>9?1:saveIndex;
		return saveIndex;
	}
	
	public static boolean save() {
		int index=savePostion();
		String savePath=UPath.projectPath("/save/save"+index+".stm");
		File f=new File(UIO.fileDirectory(savePath));
		f.mkdirs();
		
		RunningStateEvent event = (RunningStateEvent) M.e().getStateEvent(GameState.running);
		ArrayBase array = event.getArray();
		
		GameInfo info = array.getInfo();
		
		FileOutputStream fos=null;
		try{
			fos=new FileOutputStream(savePath);
			//魔数
			fos.write(10);
			fos.write(27);
			//版本
			fos.write(00);
			fos.write(01);
			//宽高
			fos.write(info.getHcount());
			fos.write(info.getVcount());
			//所用时间
			int time = event.getTime().getVal();
			for(int i=0;i<4;i++) {
				fos.write(time % 256);
				time/=256;
			}
			//剩余氪金数
			time=array.getKcount();
			fos.write(time % 256);
			time/=256;
			fos.write(time % 256);
			
			fos.write(info.getLevel().getVal());
			
			for(int i:array.getArray()) {
				fos.write(i);
			}
			
			SaveFile saveFile = new SaveFile(new Date(), info.getLevel().getVal(), info.getHcount(), info.getVcount(), event.getTime().getVal(), array.getKcount());
			saveFile.setPath(new File(savePath));
			list.add(saveFile);
			Collections.sort(list);
			
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(fos!=null) {
				try { fos.close(); } catch (IOException e) { e.printStackTrace(); }
			}
		}
		return false;
	}

	public static List<SaveFile> getList() {
		return list;
	}
}
